package de.koller.altitude.input;

import de.koller.altitude.ANode;
import de.koller.oceanFramework.OceanException;
import de.koller.oceanFramework.gl.util.InputGL;
import de.koller.oceanFramework.tree.Child;
import java.util.HashSet;
import java.util.Set;
import org.lwjgl.input.Keyboard;

public class AInput extends ANode {
	@Child private final InputGL input = new InputGL();

	public final Set<IMouseMotionHandler> mouseMotionHandlers = new HashSet<>();
	public final Set<IKeyDownHandler> keyDownHandlers = new HashSet<>();
	private boolean mouseGrabbed = true;

	private IKeyDownHandler currentKDHandler = null;
	@Override
	protected void init() {
		super.init();
		
		input.grabMouse();
	}
	
	public boolean isKeyDown( IKeyDownHandler handler, int key ) {
		if( handler != currentKDHandler )
			throw new OceanException();
		
		return input.isKeyDown( key );
	}
	
	@Override
	protected void update( int elapsedTime ) {
		super.update( elapsedTime );
		
		if( input.isKeyPressed( Keyboard.KEY_F12 ) )
			aroot.stop();
		if( input.isKeyPressed( Keyboard.KEY_ESCAPE ) ) {
			mouseGrabbed = !mouseGrabbed;
			if(  mouseGrabbed ) input.grabMouse();
			if( !mouseGrabbed ) input.unGrabMouse();
		}
			
		
		for( IMouseMotionHandler h : mouseMotionHandlers )
			h.mouseMoved( input.getMouseDX(), input.getMouseDY() );
		
		for( IKeyDownHandler h : keyDownHandlers ) {
			currentKDHandler = h;
			h.keyDown( this );
		}
		currentKDHandler = null;
			
	}
	
}
